package com.dcy.file.util;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.dcy.common.enums.AdminApiErrorCode;
import com.dcy.common.exception.BusinessException;
import com.dcy.file.properties.MinioProperties;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;

/**
 * @Author：dcy
 * @Description: minio 工具类
 * @Date: 2021/4/20 14:35
 */
@Getter
@RequiredArgsConstructor
@Slf4j
public class MinioUtil {

    public static final int DEFAULT_MULTIPART_SIZE = 10 * 1024 * 1024;

    private final MinioProperties minioProperties;

    private final MinioClient minioClient;

    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws Exception
     */
    public String uploadFile(MultipartFile file) {
        // yyyy-MM-dd/yyyyMMddHHmmssSSS-filename
        final String filePath = StrUtil.format("%s/%s-%s",
                DateUtil.today(),
                DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN),
                file.getOriginalFilename());
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getBucket())
                    .object(filePath)
                    .stream(file.getInputStream(), -1, DEFAULT_MULTIPART_SIZE)
                    .build());
        } catch (Exception e) {
            log.error("uploadFile {}", e.getMessage());
            throw new BusinessException(AdminApiErrorCode.FILE_UPLOAD_ERROR);
        }
        return filePath;
    }

    /**
     * 下载文件
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    public InputStream downloadFile(String fileName) {
        try {
            return minioClient.getObject(GetObjectArgs.builder()
                    .bucket(minioProperties.getBucket())
                    .object(fileName).build());
        } catch (Exception e) {
            log.error("downloadFile {}", e.getMessage());
            throw new BusinessException(AdminApiErrorCode.FILE_DOWNLOAD_ERROR);
        }
    }

    /**
     * 删除文件
     *
     * @param fileName
     * @throws Exception
     */
    public void removeFile(String fileName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(minioProperties.getBucket())
                    .object(fileName).build());
        } catch (Exception e) {
            log.error("removeFile {}", e.getMessage());
            throw new BusinessException(AdminApiErrorCode.FILE_REMOVE_ERROR);
        }
    }
}
